package org.phalanx.map.xml;

import org.phalanx.map.MapTile;
import org.phalanx.map.MapTileSet;
import org.phalanx.map.PhalanxMapTerrain;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;

public class TileSetXMLFileHandler extends DefaultHandler {
	private boolean isTagClosed;
	private boolean isTileSetAuthorized = false;
	private String currentContextTag;
	MapTileSet mapTileTable;
	
	public TileSetXMLFileHandler(MapTileSet p){
		mapTileTable = p;
	}
	@Override
	public void characters(char[] arg0, int arg1, int arg2) throws SAXException {
		String data = new String(arg0, arg1, arg2);

		if (!isTagClosed){
			if (currentContextTag.equalsIgnoreCase("name")){
				mapTileTable.setTileSetName(data);
			}
			if (currentContextTag.equalsIgnoreCase("author")){
				mapTileTable.setAuthorName(data);
			}
			else if (currentContextTag.equalsIgnoreCase("email")){
				mapTileTable.setEmailAddress(data);
			}
			else if (currentContextTag.equalsIgnoreCase("country")){
				mapTileTable.setCountry(data);
			}
		}
		super.characters(arg0, arg1, arg2);
	}

	@Override
	public void endDocument() throws SAXException {
		// TODO Auto-generated method stub
		super.endDocument();
	}

	@Override
	public void endElement(String arg0, String arg1, String arg2)
			throws SAXException {
		// TODO Auto-generated method stub
		isTagClosed = true;
		super.endElement(arg0, arg1, arg2);
	}

	@Override
	public void error(SAXParseException arg0) throws SAXException {
		// TODO Auto-generated method stub
		super.error(arg0);
	}

	@Override
	public void startDocument() throws SAXException {
		// TODO Auto-generated method stub
		super.startDocument();
	}

	@Override
	public void startElement(String arg0, String localName, String qName,
			Attributes attr) throws SAXException {
		isTagClosed = false;
		currentContextTag = localName;
		if (currentContextTag.equalsIgnoreCase("TileMap")){
			isTileSetAuthorized = true;
		}
		else if (currentContextTag.equalsIgnoreCase("Tile") && isTileSetAuthorized){
			String referenceName = attr.getValue("name");
			String terrainType = attr.getValue("terraintype");
			String imageRef = attr.getValue("imageref");
			
			if (referenceName != null && terrainType != null && imageRef != null){
				MapTile m = new MapTile();
				m.setTerrain(new PhalanxMapTerrain(terrainType));
				m.setImageReference(imageRef);
				mapTileTable.setMapTile(referenceName, m);
			}
		}
		super.startElement(arg0, localName, qName, attr);
	}

}
